package ai

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"project-info/src/model"
	"time"
)

// 通用AI模型调用方法
func callAIModelWithRequest(reqBody OpenAIRequest) (string, error) {
	jsonData, err := json.Marshal(reqBody)
	if err != nil {
		return "", err
	}

	fmt.Println(string(jsonData))
	req, err := http.NewRequest("POST", model.C.AI.ApiUrl, bytes.NewBuffer(jsonData))
	if err != nil {
		return "", err
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+model.C.AI.ApiKey)

	client := &http.Client{Timeout: 60 * time.Second} // 增加超时时间以支持多轮对话
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("AI API返回错误状态码: %d, 响应: %s", resp.StatusCode, string(body))
	}

	var aiResp OpenAIResponse
	if err := json.Unmarshal(body, &aiResp); err != nil {
		return "", err
	}

	if len(aiResp.Choices) == 0 {
		return "", fmt.Errorf("AI API返回空响应")
	}

	return aiResp.Choices[0].Message.Content, nil
}

// 工具执行结果
type ToolExecutionResult struct {
	ToolName   string                 `json:"toolName"`
	Parameters map[string]interface{} `json:"parameters"`
	Success    bool                   `json:"success"`
	Result     interface{}            `json:"result"`
	Summary    string                 `json:"summary"`
	Timestamp  time.Time              `json:"timestamp"`
}
